//ajax 请求
import axios from 'axios';
import { Toast } from 'mint-ui';
import Element from 'element-ui';
import { Notification } from 'element-ui';
import router from '@/router'
import store from '../store/index.js'



const service = axios.create({

  baseURL: '/api',  //本地
  // baseURL: 'https://test.yicheng120.com:981/yc-hospital-blood-sugar',  //测试
  timeout: 100000,
  transformRequest: [function (data) {//请求预处理函数
    return data
  }],
  // headers: {ContentType: "application/json"},
  // withCredentials: true,    //跨域
})

// 设置请求类型
service.defaults.headers['Content-Type'] = 'application/json'

// 获取token
function setToke() {
  // alert(11)
  const token = store.state.token || JSON.parse(sessionStorage.getItem("token"))
  // const token = JSON.parse(sessionStorage.getItem("token"))
  service.interceptors.request.use(config => {
    if (token) {
      // 过滤taken
      if (config.url != '/auth') {
        config.headers.common['Authorization'] = token;
      }
    }
    return config;
  },
    error => {
      // 对请求错误做些什么
      Toast({
        message: error,
        position: 'center',
      });
      return Promise.reject(error);
    }
  );
}

setToke()




//对数组的方法进行重写
const ajaxMethod = ['get', 'post']
const api = {}
let that = this;

ajaxMethod.forEach((method) => {
  api[method] = function (url, data) {
    return new Promise(function (resolve, reject) {
      service[method](url, data)
        .then((response) => {
          if (response.status == 200) {
            let data = response.data;
            if (data.code == '0' || data.code == '200') {
              resolve(data)
            } else {
              if (data.code == '20023') {
                Notification.error({
                  duration: 500,
                  title: '提示',
                  position: "top-left",
                  message: "登录失效正在跳转登录认证页...",
                  onClose: () =>{
                    router.push('/login');
                    // 解决token失效F5刷新回到登录页登录页面不刷新携带上次Token访问的问题
                    let Timeout = setTimeout(() =>{
                      window.location.reload()
                    });
                    Timeout = null
                  }
                });
              } else {
                Notification.error({
                  duration: '2000',
                  title: '提示',
                  message: data.msg || data.message
                });
                reject(data)
              }
            }
          } else if (response.status == 5000) {
            router.push("/404")
            Toast({
              message: "网络丢失...",
              position: 'center',
            });
          } else {
            Notification.success({
              duration: '2000',
              title: '提示',
              message: data.msg || data.message
            });
          }
        })
        .catch(function (error) {
          return error
        })
    })
  }
})

export default api

export { setToke }
